﻿using FrameWork.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.EntityFrameworkCore.Internal;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;

namespace FrameWork
{
    [AttributeUsage(AttributeTargets.All)]
   public class ActionRedirectAttribute : ActionFilterAttribute
   {
        private readonly JsonSerializerSettings _jsonSerializerSettings = new JsonSerializerSettings
        {
            DateFormatHandling = DateFormatHandling.MicrosoftDateFormat,
            DateFormatString = "yyyy-MM-dd HH:mm:ss",
            ContractResolver = new CamelCasePropertyNamesContractResolver(),
            Formatting = Formatting.Indented
        };

       public override void OnActionExecuting(ActionExecutingContext filterContext)
       {
            var request = filterContext.HttpContext.Request;
            request.Headers.TryGetValue("redirectHost", out var redirectHosts);

            if (!redirectHosts.Any())
            {
                base.OnActionExecuting(filterContext);
                return;
            }

            var redirectHost = redirectHosts.FirstOrDefault();
            if (string.IsNullOrWhiteSpace(redirectHost))
            {
                base.OnActionExecuting(filterContext);
                return;
            }

            redirectHost = redirectHost.StartsWith("http") ? redirectHost : $"http://{redirectHost}";


            var url = $"{redirectHost}{request.Path.Value}";
            var method = request.Method.ToLower() == "get" ? TimHttp.Method.Get : TimHttp.Method.Post;

            request.Headers.TryGetValue("Authorization", out var authorizations);
            var authorization = authorizations.FirstOrDefault();
            var header = new Dictionary<string, string>();
            if (!string.IsNullOrWhiteSpace(authorization)) header.Add("Authorization", authorization);

            var queryBuilder = new StringBuilder();
            foreach (var item in request.Query)
            {
                queryBuilder.Append($"{item.Key}={item.Value.FirstOrDefault()}");
            }

            string param;
            if (method == TimHttp.Method.Get)
            {
                param = string.IsNullOrWhiteSpace(queryBuilder.ToString()) ? filterContext.ActionArguments?.FirstOrDefault().Value?.ToJsonStr() : queryBuilder.ToString();
            }
            else
            {
                param = filterContext.ActionArguments?.FirstOrDefault().Value?.ToJsonStr();
            }

            var content = new TimHttpContent
            {
                CookieData = new CookieCollection(),
                Header = header,
                ContentType = "application/json",
                Method = method,
                Url = url,
                Param = param ?? ""
            };
            var html = new TimHttp().PostOrGet(ref content);

            if (string.IsNullOrWhiteSpace(html))
            {
                filterContext.Result = PublicTool.ReturnError("05系统错误,请联系管理员").Result;
            }
            else
            {
                var json = html.TryParse() ?? new JObject();

                filterContext.Result = new JsonResult(json, _jsonSerializerSettings)
                {
                    ContentType = "application/json; charset=utf-8",
                    StatusCode = 200,
                    Value = json
                };
            }
        }
    }
}
